(function(){
  'use strict';

  if (window.Api) return;

  var API_BASE = window.API_BASE || 'http://43.153.150.144:8080';

  function getToken(){
    if (window.Auth && typeof window.Auth.getToken === 'function') return window.Auth.getToken();
    if (window.AppApi && typeof window.AppApi.getToken === 'function') return window.AppApi.getToken();
    return '';
  }

  async function request(method, path, body, needAuth){
    var headers = {};
    if (body) headers['Content-Type'] = 'application/json';
    if (needAuth){
      var t = getToken();
      if (t) headers.Authorization = 'Bearer ' + t;
    }
    var res = await fetch(API_BASE + path, {
      method: method,
      headers: headers,
      body: body ? JSON.stringify(body) : undefined
    });
    return res;
  }

  async function jsonOrThrow(res){
    if (!res.ok) throw new Error('HTTP ' + res.status);
    var ct = res.headers.get && res.headers.get('content-type');
    if (ct && ct.indexOf('application/json') >= 0) return res.json();
    return res.text();
  }

  window.Api = { request: request, jsonOrThrow: jsonOrThrow, getToken: getToken };
})();


